<template>
<div>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="父部门id" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择父部门id" />
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitForm">确 定</el-button>
    <el-button @click="cancel">取 消</el-button>
  </div>
</div>
</template>

<script>
import { listDept,   addDept } from "@/api/demo/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AddMixin from "@/minixs/tree/add"
export default {
  name: "DeptAdd",
  mixins:[AddMixin],
  components: {
    Treeselect
  },
  data(){
    return{
      form: {
              id: null,

                parentId: this.parentId || undefined,

              deptName: null,
              delFlag: null,
              createBy: null,
              createTime: null,
              updateBy: null,
              updateTime: null,
              ancestors: null,
              parentName: null,
              remark: null
      },
      // 表单校验
      rules: {
      },
      // 测试部门树选项
      deptOptions:[]
    }
  },
  mounted() {
    this.getTreeselect();
  },
  methods:{
    /**
     * 保存数据
     * @returns {Promise<unknown>}
     */
    save() {
      return new Promise((resolve, reject) => {
        addDept(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          resolve();
        }).catch(reject);
      })
    },

    /** 转换测试部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children
      };
    },

    /** 查询测试部门下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        const data = { id: 0, deptName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.deptOptions = [data];
      });
    },

  }
};
</script>
